package net.lazyandroid.namewars.model;

import java.util.ArrayList;
import java.util.Date;

import net.lazyandroid.namewars.utils.IOUtils;
import net.lazyandroid.namewars.utils.Log;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

/**
 * @author Shane
 *
 */
public class LocalAccessor
{

    private static final String LOG_TAG = "LocalAccessor";
	private static final String DATABASE_NAME = "nameswar.db";	

	
	private static final String SQL_CREATE_TABLE_FIGHT_RECORD = 
							"CREATE TABLE IF NOT EXISTS FightRecordItem("
						    + "id INTEGER PRIMARY KEY,"
						    + "challenger TEXT,"
						    + "defender TEXT,"
						    + "rounds TEXT,"
						    + "createdTime TEXT"
						    + ");";

	private SharedPreferences prefs = null;	
	private Context ctx;
	
	

	private LocalAccessor(Context ctx)
	{
		this.ctx = ctx;
		prefs = ctx.getSharedPreferences(IOUtils.PREFS_FILE, Context.MODE_PRIVATE);
		SQLiteDatabase db = openDB();
		db.execSQL(SQL_CREATE_TABLE_FIGHT_RECORD);
		db.close();
//		testDBMessage();
//		testDBFavoriteItem();
	}	

	static private LocalAccessor accessor; 
	
	public static LocalAccessor getInstance(Context context){		
		if(accessor == null){
			accessor = new LocalAccessor(context);
		}
		return accessor;
	}
	
	private SQLiteDatabase openDB()
	{		
		return ctx.openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
	}
	
	
	//insert or update(if exist) version in SharedPreferences
	public boolean updateVersion(int version) throws Exception
	{
		SharedPreferences.Editor editor = prefs.edit();
		editor.putInt("appVersion", version);
		editor.commit();
		return true;
	}
	/**
	 * @return 保存的版本号
	 */
	public int getVersion()
	{
		return prefs.getInt("appVersion", 0);
	}
	
	public void setAvailableID(long id)
	{
		SharedPreferences.Editor editor = prefs.edit();
		editor.putLong("AvailableID", id);
		editor.commit();
	}
	public long getAvailableID()
	{
		long id = prefs.getLong("AvailableID", 0);
		setAvailableID(id +1);
		Log.e("AvailableID :" + id);
		return id ;
	}
	//return null if no user saved
	/*
	public User getUser()
	{
		User ret = new User();
        ret.name = prefs.getString("username", null);
        ret.password = prefs.getString("password", null);
        ret.id = prefs.getLong("id", 0);
		return ret;
	}	
	*/
	
	//insert or update(if exist) Favorte Item in db
	public boolean updateRecord(FightRecordItem item) throws Exception
	{
		Log.d("updateRecord.....");
		ContentValues values = new ContentValues();	
		values.put("challenger", FighterAsset.encode(item.challenger));    
		values.put("defender", FighterAsset.encode(item.defender));
		values.put("rounds", ChallengeRoundAsset.encode(item.rounds));
		values.put("createdTime", item.createdTime);
		
		SQLiteDatabase db = openDB();
		Log.d("db.isOpen() : " + db.isOpen());
		if(this.getFightRecordItem(item.id)== null)
		{//insert
			values.put("id", item.id);
			db.insertOrThrow("FightRecordItem", null, values);			
		}
		else
		{//update
		    db.update("FightRecordItem", values, "id=" + item.id, null);			
		}		
		db.close();
		
		return true;
	}
	
	public ArrayList<FightRecordItem> getFightRecordsByPage(int pageNo, int size) 
														throws Exception
	{
		Log.e("getFightRecordsByPage " );
		
		SQLiteDatabase db = openDB();	
        Cursor c = db.query("FightRecordItem", null, null, null, null, null, "id");  
        ArrayList<FightRecordItem> ret = new ArrayList<FightRecordItem>();		
        int begin = c.getCount() - (pageNo - 1) * size - 1;
        if(c.moveToPosition(begin))
        {
        	ret.add(buildFightRecord(c));
        }
        int i = 0;
        while(i != size - 1 && c.moveToPrevious()) 
        {
        	ret.add(buildFightRecord(c));
        	i++;
        }
        
        c.close();
        db.close();
        return ret;	
   }
	
	public ArrayList<FightRecordItem> getFightRecords()
	{
		Log.e("getFightRecords " );
		
		SQLiteDatabase db = openDB();	
        Cursor c = db.query("FightRecordItem", null, null, null, null, null, "id");  
        ArrayList<FightRecordItem> ret = new ArrayList<FightRecordItem>();		
        int begin  , size ;
        begin = size = c.getCount();
        
        if(c.moveToPosition(begin-1))
        {
        	ret.add(buildFightRecord(c));
        }
        int i = 0;
        while(i < size && c.moveToPrevious()) 
        {
        	ret.add(buildFightRecord(c));
        	i++;
        }
        
        c.close();
        db.close();
        
        return ret ;
	}
	
	private FightRecordItem buildFightRecord(Cursor c) 
	{
		FightRecordItem ret = new FightRecordItem(); 
        ret.id = c.getLong(0);
        ret.challenger = FighterAsset.decode(c.getString(1)); 
        ret.defender = FighterAsset.decode(c.getString(2));
        ret.rounds = ChallengeRoundAsset.decode(c.getString(3));
        ret.createdTime = c.getString(4);
        //c.close();
		return ret; 
	}


	//return null if no item found
	public FightRecordItem getFightRecordItem(long id) throws Exception
	{
		Log.e("getFightRecordItem " );
		FightRecordItem ret = null;
		SQLiteDatabase db = openDB();
        Cursor c = db.query("FightRecordItem", null, "id="+id, null, null, null, null);        
        if (c.moveToFirst()) {            
            ret = buildFightRecord(c);
        }
        c.close();
        db.close();
        return ret;
	
	}	
	public int deleteFightRecordItem(long id) throws Exception
	{
		Log.e("deleteFightRecordItem " );
		SQLiteDatabase db = openDB();
		int count = db.delete("FightRecordItem", "id="+id, null );
		db.close();
		return count;
	}
	
	public void clearFightRecords() 
	{
		SQLiteDatabase db = openDB();	
		db.delete("FightRecordItem", null, null);
		db.close();
	}
	
	public boolean isFightRecordsEmpty()
	{
		Log.d("isFightRecordsEmpty ");
		SQLiteDatabase db = openDB();	
		Cursor c = db.query("FightRecordItem", null, null, null, null, null, null);
		boolean ret = c.getCount() == 0 ? true : false ;
		c.close();
		db.close();
		return ret;
	}
}
